<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { House, TurnOff } from '@element-plus/icons-vue';
import { userLoginService, userRegisterService, getUserInfoService } from '../api/user'; // 确保导入的是命名导出
import { useTokenStore } from "../stores/token.js";

const tokenStore = useTokenStore();
const url = 'src/img/横式标志.png';
// 获取用户信息的方法
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfoService(userName); // 获取 userName 的值
    console.log(response);
    if (response.data) {
      userInfo.value = response.data;  // 更新 userInfo
    }
  } catch (error) {
    console.error('获取用户信息失败', error); // 输出详细的错误信息
    ElMessage.error(`获取用户信息失败: ${error.message || error}`); // 显示详细的错误信息
  }
};
const showLoginDialog = ref(false); // 控制登录弹窗
const isLoggedIn = ref(false); // 是否登录
const userName = ref('未登录'); // 登录用户名
const userInfo = ref([]);
const loginForm = ref({
  username: '',
  password: '',
});
const registerForm = ref({
  username: '',
  email: '',
  password: '',
});
const isLoginMode = ref(true); // 控制登录与注册模式
const handleLogin = async () => {
  // 调用后端登录接口
  try {
    const response = await userLoginService(loginForm.value);
    console.log(response.code);

    // 判断是否登录成功
    if (response.code === 0) {
      // 登录成功，设置登录状态
      isLoggedIn.value = true;
      userName.value = loginForm.value.username;
      showLoginDialog.value = false;
      fetchUserInfo();
      // 假设 token 是在 response 中的某个字段（例如 response.token）
      const token = response.token;
      console.log(token)
      if (token) {
        // 把得到的 token 存储到 Pinia 中
        tokenStore.setToken(token);
        // 登录成功提示
        ElMessage.success('登录成功');  // 显示成功提示
        setCookie('username', loginForm.value.username, 7);
        //setCookie('userId',response.data.userId,7)
      } else {
        // 如果后端没有返回 token，提示用户
        alert('未获取到 token，请重试');
      }
    } else {
      // 登录失败，提示错误信息
      alert(response.data.message || '登录失败');
    }
  } catch (error) {
    // 捕获异常并提示
    ElMessage.error('登录失败，请重试');
  }
};
// 设置 cookie
function setCookie(name, value, days) {
  const expires = new Date();
  expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000)); // 设置过期时间
  document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/`; // path=/ 确保 cookie 在整个网站中都有效
}

const router = useRouter(); // 路由实例


const handleRegister = async () => {
  if (registerForm.value.username && registerForm.value.email && registerForm.value.password) {
    try {
      // 调用注册接口
      const response = await userRegisterService(registerForm.value);
      if (response.code == 0) {
        alert('注册成功，请登录！');
        isLoginMode.value = true; // 切换到登录模式
      } else {
        alert(response.data.message || '注册失败');
      }
    } catch (error) {
      alert('注册失败，请重试');
    }
  } else {
    alert('请完整填写注册信息');
  }
};

const handleLogout = () => {
  isLoggedIn.value = false;
  userName.value = '未登录';
};

const navigateToHome = () => {
  router.push('/'); // 跳转到首页
};
const navigateToKeyword = () => {
  router.push('/keyword'); // 跳转到关键词页面
};
const navigateToTrend = () => {
  router.push('/trend'); // 跳转到趋势页面
};
const navigateToUserInfo = () => {
  router.push('/userinfo'); // 跳转到个人主页页面
};
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="grid-content ep-bg-purple" />
          </el-col>
          <el-col :span="4">
            <div class="grid-content ep-bg-purple" style="cursor: pointer;" @click="navigateToHome">
              <el-image style="width: 200px; height: 50px" :src="url" :fit="contain" />
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content ep-bg-purple">
              <div class="title-1"
                style="display: flex; justify-content: center; align-items: center; padding-right: 60px;">
                <el-button
                  style="font-size: 23px; font-weight: 45; font-family: 'Microsoft JhengHei UI Light'; color: #0872AF;"
                  text @click="navigateToKeyword">
                  KeyWord
                </el-button>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content ep-bg-purple">
              <div class="title-2"
                style="display: flex; justify-content: center; align-items: center; padding-right: 500px;">
                <el-button
                  style="font-size: 23px; font-weight: 45; font-family: 'Microsoft JhengHei UI Light'; color: #0872AF;"
                  text @click="navigateToTrend">
                  Hot-Trend
                </el-button>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content ep-bg-purple" />
          </el-col>
          <el-col :span="4">
            <div class="grid-content ep-bg-purple">
              <el-dropdown placement="bottom-start">
                <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="!isLoggedIn" @click="showLoginDialog = true">
                      <p style=" color:black">去登录</p>
                    </el-dropdown-item>
                    <template v-else>
                      <el-dropdown-item>
                        <div class="User-Info">
                          <h4>{{ userName }}</h4>
                          <!-- 动态设置 'vip' 或 '普通用户' 样式 -->
                          <p
                            :style="userInfo.permission === 1 ? { color: 'red' } : { color: 'black', fontSize: '12px' }">
                            {{ userInfo.permission === 1 ? 'VIP' : '普通用户' }}
                          </p>
                        </div>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <div class="User-Space" @click="navigateToUserInfo">
                          <el-icon>
                            <House />
                          </el-icon>
                          <p style="color: black;">个人空间</p>
                        </div>
                      </el-dropdown-item>
                      <el-dropdown-item @click="handleLogout">
                        <div class="Sign-Out">
                          <el-icon>
                            <TurnOff />
                          </el-icon>
                          <p style="color: black;">退出登录</p>
                        </div>
                      </el-dropdown-item>
                    </template>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-col>
        </el-row>
      </el-header>
    </el-container>
    <el-divider style="border-width: 1.5px; border-color:black;" />

    <!-- 登录弹窗 -->
    <el-dialog v-model="showLoginDialog" title="登录" width="30%"
      :style="{ 'text-align': 'center', 'font-family': 'Microsoft JhengHei UI Light' }">
      <div v-if="isLoginMode">
        <el-form :model="loginForm" label-width="80px">
          <el-form-item label="用户名" :style="{ 'font-family': 'Microsoft JhengHei UI Light' }">
            <el-input v-model="loginForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" :style="{ 'font-family': 'Microsoft JhengHei UI Light' }">
            <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item :style="{ 'display': 'flex', 'justify-content': 'center' }">
            <el-button type="primary" @click="handleLogin"
              :style="{ 'font-family': 'Microsoft JhengHei UI Light' }">登录</el-button>
            <el-button type="text" @click="isLoginMode = false"
              :style="{ 'font-family': 'Microsoft JhengHei UI Light' }">去注册</el-button>
          </el-form-item>

        </el-form>
      </div>
      <div v-else>
        <el-form :model="registerForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="registerForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRegister">注册</el-button>
            <el-button type="text" @click="isLoginMode = true">已有账号？去登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.title-1 {
  margin-top: 10px;
}

.title-2 {
  margin-top: 10px;
  margin-right: -100px;
}

.User-Info {
  display: flex;
  align-items: center;
}

h4 {
  margin: 0;
  padding: 0 10px;
}

p {
  margin: 0;
  padding: 0 10px;
  color: brown;
}

.User-Space {
  display: flex;
  align-items: center;
}

.Sign-Out {
  display: flex;
  align-items: center;
}

.el-header {
  height: 35px;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
  margin-top: 5px;
}

.grid-content {
  height: 30px;
}

.el-dropdown-menu {
  text-align: center;
  width: 170px;
}

.el-dropdown-item {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
</style>
